package com.linuxgt.baidu.zhidao;

import javax.swing.table.DefaultTableModel;
import java.util.Calendar;
import java.util.GregorianCalendar;

/**
 * Created by liuteng on 15-6-16.
 */
public class ZDCalendar {
    private int lastTime;
    private DefaultTableModel dtm = new DefaultTableModel();

    public static void main(String[] args) {
        ZDCalendar zdCalendar = new ZDCalendar();
        System.out.println(zdCalendar.getDaysOfMonth(2015, 5));
        zdCalendar.showCalendar(2015, 5,new GregorianCalendar(2015,5,1));
        zdCalendar.showCalendar2(2015, 5, new GregorianCalendar(2015,5,1));
    }


    public void showCalendar(int localYear, int localMonth, Calendar cld) {
        //         某年某月有几天                            当前天是一周的第几天
        int Days = getDaysOfMonth(localYear, localMonth) + cld.get(Calendar.DAY_OF_WEEK) - 1;
        Object[] ai = new Object[7];//一周七天数组
        lastTime = 0;//天数计数器
        for (int i = cld.get(Calendar.DAY_OF_WEEK); i <= Days; i++) {//开始循环构造日历表格
            ai[i % 7] = String.valueOf(i - cld.get(Calendar.DAY_OF_WEEK) - 1);//从当前天所在一周的第几天开始初始化第一行
            if (i % 7 == 6) {//一周最后一天起新行
                dtm.addRow(ai);
                ai = new Object[7];
                lastTime++;
            }
        }
        dtm.addRow(ai);
    }

    public void showCalendar2(int localYear, int localMonth,Calendar cld) {
        int day4week=cld.get(Calendar.DAY_OF_WEEK) - 1;
        int days = getDaysOfMonth(localYear, localMonth);
        Object[] ai = new Object[7];
        lastTime = 0;
        printCalendarCn(new String[]{"一", "二", "三", "四", "五", "六", "日"});
        for (int i = day4week; i <= days; i++) {
            ai[(i-1) % 7] = String.valueOf(i);
            if (i % 7 == 0) {
                printCalendar(ai);
                ai = new Object[7];
                lastTime++;
            }
        }
        printCalendar(ai);
    }

    private void printCalendar(Object[] ai) {
        for (int i = 0; i < ai.length; i++) {
            System.out.printf("%4s",ai[i]==null?"":ai[i]);
        }
        System.out.println();
    }
    private void printCalendarCn(Object[] ai) {
        for (int i = 0; i < ai.length; i++) {
            System.out.printf("%3s",ai[i]==null?"":ai[i]);
        }
        System.out.println();
    }

    private int getDaysOfMonth(int localYear, int localMonth) {
        Calendar calendar = new GregorianCalendar(localYear, localMonth, 0);
        return calendar.get(Calendar.DAY_OF_MONTH);
    }
}
